﻿param($computerNames,$exportPath)

$parentPath=(Split-Path $PSCommandPath -Parent)

$scriptBlock= 
{
    param($computerName,$exportPath)
    Write-Host "Capturing computer GPResults for $computerName"
    gpresult /S $computerName /SCOPE COMPUTER /X $exportPath\$computerName`_gpresult.xml
}


foreach($computerName in $computerNames)
{
    $jobName="Gather GPResult from $computerName"

    $jobStarted=$false

    while(-not $jobStarted)
    {
        $activeJobCount=(Get-Job -Name "Gather GPResult from *" | Where {$_.State -eq "Running"} | Measure-Object).Count
        if($activeJobCount -le 30)
        {
            Start-Job -Name $jobName -ScriptBlock $scriptBlock -ArgumentList $computerName,$exportPath
            $jobStarted=$true
        }
        else
        {
            Start-Sleep -Seconds 5
        }
    }
}

do
{
    Get-Job "Gather GPResult from *" | Receive-Job
    Get-Job "Gather GPResult from *" | where {$_.State -eq "Completed"} | Remove-Job
    Start-Sleep -Seconds 15   
}
while(((Get-Job -Name "Gather GPResult from *" | Where {$_.State -eq "Running"} | Measure-Object).Count) -gt 0)
